<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" class="optimized-search-form">
      <el-form-item label="所属内容ID" prop="contentId" label-width="100px">
        <el-input
          v-model="queryParams.contentId"
          placeholder="请输入所属内容ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="章节标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入章节标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="章节时长" prop="duration">
        <el-input
          v-model="queryParams.duration"
          placeholder="请输入章节时长"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否免费试看" prop="isFree" label-width="100px">
        <el-input
          v-model="queryParams.isFree"
          placeholder="请输入是否免费试看(1是/0否)"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input
          v-model="queryParams.sort"
          placeholder="请输入排序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="optimized-button-group mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['chapter:chapter:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['chapter:chapter:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['chapter:chapter:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['chapter:chapter:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chapterList" @selection-change="handleSelectionChange" class="optimized-table">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="章节ID" align="center" prop="id" />
      <el-table-column label="所属内容ID" align="center" prop="contentId" />
      <el-table-column label="章节标题" align="center" prop="title" />
      <el-table-column label="视频播放地址" align="center" prop="videoUrl" width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.videoUrl">
            <video
              v-if="isVideoFile(scope.row.videoUrl)"
              :src="scope.row.videoUrl"
              controls
              width="100"
              height="60"
              preload="metadata"
              style="border-radius: 4px;"
            >
              您的浏览器不支持视频播放
            </video>
            <image-preview
              v-else
              :src="scope.row.videoUrl"
              :width="50"
              :height="50"
            />
          </div>
          <span v-else style="color: #999;">暂无视频</span>
        </template>
      </el-table-column>
      <el-table-column label="章节时长" align="center" prop="duration" />
      <el-table-column label="是否免费试看" align="center" prop="isFree" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <div class="table-operation-buttons">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['chapter:chapter:edit']"
           class="edit-text">修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['chapter:chapter:remove']"
           class="delete-text">删除</el-button>
        </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程章节对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body class="optimized-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属内容ID" prop="contentId" label-width="100px">
          <el-input v-model="form.contentId" placeholder="请输入所属内容ID" />
        </el-form-item>
        <el-form-item label="章节标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入章节标题" />
        </el-form-item>
        <el-form-item label="视频播放地址" prop="videoUrl" label-width="110px">
<!--          <el-input v-model="form.videoUrl" placeholder="请输入视频播放地址" />-->
          <div style="margin-top: 10px;">
            <el-button type="primary" size="small" @click="handleVideoUpload">上传视频文件</el-button>
            <span style="margin-left: 10px; color: #999; font-size: 12px;">
              支持格式：mp4, avi, mov, wmv, flv, webm, mkv, m4v, 3gp, ogv
            </span>
          </div>
        </el-form-item>
        <el-form-item label="章节时长" prop="duration">
          <el-input v-model="form.duration" placeholder="请输入章节时长" />
        </el-form-item>
        <el-form-item label="是否免费试看" prop="isFree" label-width="100px">
          <el-select v-model="form.isFree" placeholder="请选择是否免费试看(1是/0否)" >
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listChapter, getChapter, delChapter, addChapter, updateChapter } from "@/api/chapter/chapter"
import request from '@/utils/request'

export default {
  name: "Chapter",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程章节表格数据
      chapterList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contentId: null,
        title: null,
        videoUrl: null,
        duration: null,
        isFree: null,
        sort: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contentId: [
          { required: true, message: "所属内容ID不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "章节标题不能为空", trigger: "blur" }
        ],
        // videoUrl: [
        //   { required: true, message: "视频播放地址不能为空", trigger: "blur" }
        // ],
        duration: [
          { required: true, message: "章节时长不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询课程章节列表 */
    getList() {
      this.loading = true
      listChapter(this.queryParams).then(response => {
        this.chapterList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        contentId: null,
        title: null,
        videoUrl: null,
        duration: null,
        isFree: null,
        sort: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加课程章节"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getChapter(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改课程章节"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateChapter(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addChapter(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除课程章节编号为"' + ids + '"的数据项？').then(function() {
        return delChapter(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('chapter/chapter/export', {
        ...this.queryParams
      }, `chapter_${new Date().getTime()}.xlsx`)
    },
    /** 判断是否为视频文件 */
    isVideoFile(url) {
      if (!url) return false
      const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv', '.m4v', '.3gp', '.ogv']
      return videoExtensions.some(ext => url.toLowerCase().includes(ext))
    },
    /** 处理视频上传 */
    handleVideoUpload() {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = 'video/*'
      input.onchange = (e) => {
        const file = e.target.files[0]
        if (file) {
          this.uploadVideoFile(file)
        }
      }
      input.click()
    },
    /** 上传视频文件 */
    uploadVideoFile(file) {
      const formData = new FormData()
      formData.append('file', file)

      this.$modal.loading("正在上传视频文件，请稍候...")

      // 使用request上传视频文件
      request({
        method: 'post',
        url: '/file/uploadVideo',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        this.$modal.closeLoading()
        if (response.code === 200) {
          this.form.videoUrl = response.data.url
          this.$modal.msgSuccess("视频上传成功，正在后台优化中...")
        } else {
          this.$modal.msgError(response.msg || "视频上传失败")
        }
      }).catch(error => {
        this.$modal.closeLoading()
        this.$modal.msgError("视频上传失败：" + (error.message || "网络错误"))
      })
    }
  }
}
</script>
